var $ = window.$;
var sample = require('../../sample/manager');
var frac = require('../../../util/frac');
var layer = require('../../layer/manager');
var sound = require('../../audio/sound');
var timing = require('../../timing/manager');
var timeline = require('../../timeline/ui');
var config = require('../../../core/config');
var notify = require('../../notify/ui');
var vector = require('../vector');

/**
 * 非独立模块, 作为ui的插件
 */

var ret = {
    Intent_Add_Hold: 1,
    Intent_Add_Normal: 1 << 1,
    Intent_Rect_Select: 1 << 2,
    Intent_Change_Hold: 1<< 3,
    Intent_Drag: 1<< 4,
    Intent_Select: 1<< 5,
    Intent_Cancel_Select: 1<<6,

    setUI: function (_ui) {
        this.ui = _ui;
    },

    onTaikoMouseDown: function(e){
        var note = this.ui.getNoteAtMousePos(e);
        if(note && e.which == 3){
            this.ui.deleteNote(note);
            return;
        }
        var virtualNote = this.ui.createNoteAtMousePos(e);
        var beat = virtualNote.beat;
        var beatOccupied = !note && this.ui.manager.findNote(virtualNote) != -1;
        if(virtualNote.column == -1){
            virtualNote = null;
        }else if(virtualNote.column == 6){
            //强制音乐轨都是小红脸
            virtualNote.type = 1;
            virtualNote.style = 1;
        }
        this.data = {
            note: note,
            virtualNote: virtualNote,
            startBeat: beat,
            startPos : this.ui.absPosToCanvas([e.pageX, e.pageY])
        };

        if(note){
            if(e.shiftKey && (note.style == 4 || note.style == 5)){
                //只有大黄脸和小黄脸可以拉长度
                this.intent = this.Intent_Change_Hold;
            }else{
                this.intent = this.Intent_Drag | this.Intent_Select;
            }
        }else{
            //如果一个位置beat对应了note 但是mask没有 也只能选择不能添加
            this.intent = this.Intent_Rect_Select | this.Intent_Cancel_Select;
            if(!beatOccupied && virtualNote){
                if(virtualNote.style == 4 || virtualNote.style == 5){
                    //圆脸只能拉长度和取消选择不能做框选
                    this.intent = this.Intent_Cancel_Select | this.Intent_Add_Hold;
                }else{
                    this.intent |= this.Intent_Add_Normal;
                }
            }
        }
    },

    onTaikoMouseMove: function(e){
        if(!this.data){
            return;
        }
        var data = this.data;
        var pos = this.ui.absPosToCanvas([e.pageX, e.pageY]);
        if(this.intent & this.Intent_Drag){
            this.intent = this.Intent_Drag;
            var beat = this.ui.mousePosToBeat(e);
            if(frac.compare(data.startBeat, beat) == 0){
                return;
            }
            var d = frac.subtract(beat, data.startBeat);
            var selNotes = this.ui.selectedNotes;
            if(!selNotes[data.note.id]){
                //只选了一个
                data.note.beat = frac.add(data.note.beat, d);
                if(data.note.endbeat){
                    data.note.endbeat = frac.add(data.note.endbeat, d);
                }
                if (data.note.tid >= 0) {
                    sound.offsetCell(data.note.tid, timing.beatToTime(data.note.beat));
                }
            }else{
                for(var k in selNotes){
                    var tmp = this.ui.manager.getNote(k);
                    tmp.beat = frac.add(tmp.beat, d);
                    if(tmp.endbeat){
                        tmp.endbeat = frac.add(tmp.endbeat, d);
                    }
                    if (tmp.tid >= 0) {
                        sound.offsetCell(tmp.tid, timing.beatToTime(tmp.beat));
                    }
                }
            }
            data.startBeat = beat;
            this.ui.fullUpdateNotes();
        }
        if(this.intent & this.Intent_Add_Hold){
            if(this.intent != this.Intent_Add_Hold){
                if(pos[0] - data.startPos[0] > 5){
                    this.intent = this.Intent_Add_Hold;
                }
            }else{
                var beat = this.ui.mousePosToBeat(e);
                //保证至少有1/2拍的长度
                var len = frac.subtract(beat, data.startBeat);
                var endBeat = null;
                if(frac.compare(len, [0,1,2]) > 0){
                    endBeat = beat;
                }else{
                    endBeat = frac.add(data.startBeat, [0, 1, 2]);
                }
                if(!data.virtualNote.endbeat){
                    this.makeNewNote(data.virtualNote);
                }
                data.virtualNote.endbeat = endBeat;
                this.ui.drawNotes();
            }
        }
        if(this.intent & this.Intent_Rect_Select){
            if(this.intent != this.Intent_Rect_Select){
                //还没有判定为框选
                var move = vector.subAbs(pos, data.startPos);
                if(move[0] < 20 && move[1] < 20){
                    return;
                }
            }
            this.intent = this.Intent_Rect_Select;  //排他
            if(!data.rectBeat){
                //记录开始选择的beat
                data.rectBeat = this.ui.mousePosToBeat(data.startPos);
                data.startTime = sound.stableTime();
                this.ui.select.show();
            }
            var size = vector.subAbs(pos, data.startPos);
            var conf = {
                width: size[0],
                height: size[1]
            };
            if(pos[0] < data.startPos[0]){
                conf.left = pos[0];
            }else{
                conf.left = data.startPos[0];
            }
            //conf.left += this.ui.offset[0];
            if(pos[1] < data.startPos[1]){
                conf.top = pos[1];
            }else{
                conf.top = data.startPos[1];
            }
            this.ui.select.css(conf);
        }
        if((this.intent & this.Intent_Rect_Select) > 0 || (this.intent & this.Intent_Drag) > 0){
            var l1 = this.ui.trackWidth * 0.8;
            var l2 = this.ui.trackWidth * 0.2;
            var delta = 0
            if(pos[0] > l1 && pos[0] > this.data.startPos[0]){
                delta = Math.ceil((pos[0] - l1) / 50);
            }else if(pos[0] < l2 && pos[0] < this.data.startPos[0]){
                delta = Math.ceil((l2 - pos[0]) / 50) * -1;
            }
            delta = delta > 4 ? 4 : delta;
            this.ui.startEdgeSeek(delta);
        }
    },

    onTaikoMouseUp: function(e){
        if(!this.data){
            return;
        }
        if((this.intent & this.Intent_Cancel_Select) > 0 && this.ui.getSelectCount() > 0){
            this.ui.cancelSelect();
            this.intent = 0;
        }
        if((this.intent & this.Intent_Add_Normal)>0 && !this.data.note && this.data.virtualNote){
            var time = this.makeNewNote(this.data.virtualNote);
            this.intent = 0;
            this.ui.checkMaxTime(time);
            this.ui.drawNotes();
            this.ui.drawNoteMasks();
        }
        if(this.intent & this.Intent_Add_Hold){
            this.intent = 0;
            this.ui.drawNoteMasks();
        }
        if(this.intent & this.Intent_Select){
            if(!e.ctrlKey){
                this.ui.cancelSelect();
            }
            this.ui.markNoteSelected(this.data.note);
            this.ui.pluginMeta.update();
            if(config.getVal(config.ITEM.PLAYSOUND)){
                this.ui.playNote(this.data.note);
            }
            this.ui.drawNotes();
            this.intent = 0;
        }
        if((this.intent & this.Intent_Rect_Select)>0 && this.data.rectBeat){
            this.ui.select.hide();
            //处理选中note
            var b1 = this.data.startBeat;
            var b2 = this.ui.mousePosToBeat(e);
            var y1 = this.data.startPos[1];
            var y2 = this.ui.absPosToCanvas([e.pageX, e.pageY])[1];
            var tmp;
            if(frac.compare(b2, b1) < 0){
                tmp = b1;
                b1 = b2;
                b2 = tmp;
            }
            if(y1 > y2){
                tmp = y1;
                y1 = y2;
                y2 = tmp;
            }
            if(!e.shiftKey){
                this.ui.selectedNotes = {};
            }
            this.ui.selectRectNotes(b1, b2, y1, y2);
            this.ui.drawNotes();
            this.ui.pluginMeta.update();
            this.intent = 0;
        }
        this.ui.stopEdgeSeek();
        this.data = null;
    },

    makeNewNote: function(note){
        var _sound = sample.getCurrent();
        if(_sound){
            note.sound = _sound;
            note.tid = -1;
        }
        this.ui.playingNote.push({
            _beat : timing.beatToFloat(note.beat),
            realNote : note
        });
        this.ui.playingNote.sort(function(a, b){
            return a._beat - b._beat > 0 ? 1 : -1
        });
        this.ui.manager.addNote(note);
        var time = this.adjustNoteSound(note);
        this.ui.adjustNoteParams(note);
        return time;
    },

    adjustNoteSound : function(note){
        var time = timing.beatToTime(note.beat) + (note.offset || 0);
        if(note.sound && note.tid == -1){ // -1的初始值在manager load的时候刷新过一遍
            note.tid = sound.addCell(sample.getFilePath(note.sound), note.vol || 30, time);
        }
        return time;
    }

};

module.exports = ret;
